package com.fise.mwtvc.socket;

import androidx.lifecycle.MutableLiveData;


import com.fise.mwtvc.socket.bean.OnlineCustomer;
import com.fise.mwtvc.socket.bean.SocketUser;

import java.net.URISyntaxException;

import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;


/**
 * author : chaoqiang.huang
 * date   : 4/8/2020  11:49 AM
 * desc   :
 */
public class SocketEngine {
    private static SocketEngine instance;

    private Socket socket;

    private SocketUser user;
    private MutableLiveData<OnlineCustomer> customerLiveData = new MutableLiveData<>();

    private SocketEngine() {

    }

    public static SocketEngine getInstance() {
        if (instance == null) {
            synchronized (SocketEngine.class) {
                if (instance == null) {
                    instance = new SocketEngine();
                }
            }
        }
        return instance;
    }

    private void addConnectListener(final SocketConnectListener listener) {
        if (listener == null) {
            return;
        }
        socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {//连接成功
            @Override
            public void call(Object... args) {
                listener.onConnected();
            }
        });
        socket.on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {//连接断开
            @Override
            public void call(Object... args) {
                listener.onDisconnect();
            }
        });
        Emitter.Listener listener2 = new Emitter.Listener() {//连接失败
            @Override
            public void call(Object... args) {
                listener.onError("连接失败");
            }
        };
        socket.on(Socket.EVENT_CONNECT_ERROR, listener2);
        socket.on(Socket.EVENT_CONNECT_TIMEOUT, listener2);
    }


    public Socket createSocket(String url, final SocketConnectListener listener) {
        try {
            if (socket == null) {
                IO.Options op = new IO.Options();
                op.transports = new String[]{"websocket"};
                op.reconnection = true;
                socket = IO.socket(url, op);
                addConnectListener(listener);
                socket.connect();
            }
            return socket;
        } catch (URISyntaxException e) {
            e.printStackTrace();
            return null;
        }
    }

    public Socket getSocket() {
        return socket;
    }

    public SocketUser getUser() {
        return user;
    }

    public void setUser(SocketUser user) {
        this.user = user;
    }

    public MutableLiveData<OnlineCustomer> getCustomerLiveData() {
        return customerLiveData;
    }

    public void setCustomerLiveData(MutableLiveData<OnlineCustomer> customerLiveData) {
        this.customerLiveData = customerLiveData;
    }

    public void stop() {
        if (socket != null && socket.connected()) {
            socket.disconnect();
        }
        socket = null;

    }
}
